import { Module } from 'vuex'
import { ILoginModule,IUserInfo } from './types'
import { IRootState } from '../types'
import { accountLogin,requestUser,requestUserMenu } from '@/network/api'
import { Data } from '@/network/typing'
import { MenuData,MenuChildren } from '@/network/menuType'
import localCache from '@/utils/cache'
import router from '@/router';

const loginModule: Module<ILoginModule, IRootState> = {
  namespaced: true,
  state() {
      return {
        token:'',
        userInfo: null,
        userMenu: null
      }
  },
  getters:{},
  mutations:{
    KEEPTOKEN( state , token: string ){
      state.token = token
    },
    KEEPUSERINFO( state , userInfo: Data ){
      state.userInfo = userInfo
    },
    KEEPUSERMENU( state , userMenu: MenuData<MenuChildren> ){
      state.userMenu = userMenu
    },
  },
  actions:{
    async accountLoginAction({ commit } , payload : IUserInfo){
      // 实现登录逻辑
      const res = await accountLogin({  name:payload.username,  password:payload.password  })
      const { id, token } = res.data
      commit('KEEPTOKEN',token)
      localCache.setCache('token',token)

      // 请求用户信息
      const userRes = await requestUser( id )
      const userInfo = userRes.data
      localCache.setCache('userInfo',userInfo)
      commit('KEEPUSERINFO',userInfo)

      // 用户菜单
      const userMenuRes = await requestUserMenu( userInfo.role.id )
      const userMenu = userMenuRes.data
      localCache.setCache('userMenu',userMenu)
      commit('KEEPUSERMENU',userMenu)

      router.push('/main')
    }
  }
}

export default loginModule
